"use strict";
/**
 * @name basics
 * 礼包商城
 */

/**
 * @name /
 * @param int id 商品ID
 * @param int num 购买数量
 * @tip 读取【shopItem】配置
 * 常规购买
 */
module.exports = async function () {
    let id = this.get('id', 'int');
    let num = this.get('num', 'int') || 1;
    if (!id || !num) {
        return this.error("args empty");
    }
    let shopBasics = this.config("shopItem", id)
    if (!shopBasics) {
        return this.error("config_not_exist", ["shopItem", id]);
    }

    this.updater.sub(shopBasics['costId'], shopBasics['costNum'] * num);
    this.updater.add(shopBasics['itemId'], shopBasics['itemNum'] * num);

    if (shopBasics.condition != 0) {
        this.updater.record.key(shopBasics.condition);
        await this.updater.data();
        let v = this.updater.record.get(shopBasics.condition);
        if (shopBasics.num > v) {
            return this.error("shop_condition_limit", shopBasics.condition, v)
        }
    }

    // for(let sub of shopBasics["sub"]){
    //     this.updater.sub(sub["id"],sub["num"] * num);
    // }

    // let {err,ret} = this.updater.item.group(shopBasics['item'],num);

    // if(err){
    //     return this.error(err,ret);
    // }
    let dkey = ['shop', 'basics', id].join(".");
    this.updater.daily.key(dkey);
    // if( shopBasics['DaylimitTimes'] || shopBasics['WeeklimitTimes'] ||  shopBasics['MonthlimitTimes']){
    this.updater.daily.add(dkey, num);
    this.updater.daily.add("record.43", num);
    this.updater.record.add(43, num);
    // }
    await this.updater.data();
    return this.library.call(this.updater, 'shop/limit', 0).then((d) => {
        if (shopBasics['DaylimitTimes'] > 0) {
            let v = this.updater.daily.get(dkey);
            let m = shopBasics['DaylimitTimes'] - v;
            if (num > m) {
                return this.error("shop_DaylimitTimes_limit", num, m)
            }
        }
    }).then(() => {
        if (shopBasics['WeeklimitTimes'] > 0) {
            return this.updater.daily.model.week(dkey).then(ret => {
                let v = ret[dkey] || 0;
                let m = shopBasics['WeeklimitTimes'] - v;
                if (num > m) {
                    return this.error("shop_WeeklimitTimes_limit", num, m);
                }
            })
        }
    }).then(() => {
        if (shopBasics['MonthlimitTimes'] > 0) {
            return this.updater.daily.model.month(dkey).then(ret => {
                let v = ret[dkey] || 0;
                let m = shopBasics['MonthlimitTimes'] - v;
                if (num > m) {
                    return this.error("shop_MonthlimitTimes_limit", num, m);
                }
            })
        }
    }).then(() => {
        return this.updater.save();
    })
}
